package com.region.integral.business_user.obtain.dao.impl;

import java.util.List;

import org.springframework.stereotype.Component;

import com.region.integral.business_user.obtain.dao.IIntegralCheckYes;
import com.region.integral.business_user.pojo.BUIEntity;
import com.region.integral.business_user.xml.Regulation;
import com.region.integral.business_user.xml.dto.CheckYes;
import com.region.integral.common_user.obtain.vo.IntegralData;
import com.region.integral.exception.IntegralException;
import com.region.integral.hibernate.BaseHibernate;
import com.region.integral.util.BusinessUserLogUtil;
import com.region.integral.util.XMLRegulationUtil;
@Component("iIntegralCheckYes")
public class IntegralCheckYesImpl extends BaseHibernate implements IIntegralCheckYes {

	@Override
	public void checkYes(int userid, IntegralData integralData)
			throws IntegralException {
		BUIEntity buiEntity = getBUIEntity(userid);
		if (buiEntity != null) {
			Regulation regulation = XMLRegulationUtil.unmarshaller2();
			List<CheckYes> checkYes = regulation.getCheckyes();
			int checkYesNum = buiEntity.getCheckYesNum();
			for (CheckYes check : checkYes) {
				if(checkYesNum == 0){
					int currIntegral = buiEntity.getCurrIntegral();
					int maxIntegral = buiEntity.getMaxIntegral();
					int totalIntegral = currIntegral+ check.getIntegral();
					buiEntity.setCurrIntegral(totalIntegral);
					if (maxIntegral < totalIntegral) {
						buiEntity.setMaxIntegral(totalIntegral);
					}
					integralData.setSuccee(true);
					hibernateTemplate.update(buiEntity);
					hibernateTemplate.save(BusinessUserLogUtil.log(userid, check.getIntegral(), "checkYes"));
				}
				if (checkYesNum!=0 && checkYesNum % check.getRate()==0) {
					int currIntegral = buiEntity.getCurrIntegral();
					int maxIntegral = buiEntity.getMaxIntegral();
					int totalIntegral = currIntegral+ check.getIntegral();
					buiEntity.setCurrIntegral(totalIntegral);
					if (maxIntegral < totalIntegral) {
						buiEntity.setMaxIntegral(totalIntegral);
					}
					integralData.setSuccee(true);
					hibernateTemplate.update(buiEntity);
					hibernateTemplate.save(BusinessUserLogUtil.log(userid, check.getIntegral(), "checkYes"));
				}
			}
			buiEntity.setCheckYesNum(checkYesNum+1);
			hibernateTemplate.update(buiEntity);
		}
		
	}

}
